package cn.apthink.utility;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

public class Util {

	private static Random random = new Random(System.currentTimeMillis());

	/**
	 * 返回随机整数
	 *
	 * @return
	 */
	public static int randInt() {
		return random.nextInt();
	}

	/**
	 * 返回指定范围内随机整数
	 *
	 * @param min
	 * @param max
	 * @return
	 */
	public static int randInt(int min, int max) {
		return min + random.nextInt(max - min);
	}

	/**
	 * 获取字符串中数字
	 *
	 * @param input
	 * @return
	 */
	public static String takeDigits(String input) {
		final StringBuilder sb = new StringBuilder(input.length());
		for (int i = 0; i < input.length(); i++) {
			final char c = input.charAt(i);
			if (c > 47 && c < 58) {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 返回全球唯一GUID
	 *
	 * @return
	 */
	public static final String guid() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	/**
	 * 返回一组全球唯一GUID
	 *
	 * @param num
	 * @return
	 */
	public static List<String> getGuidList(int num) {
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < num; i++) {
			result.add(Util.guid());
		}
		return result;
	}

	public static int Str2Int(String s) {
		return Integer.parseInt(s);
	}

	public static int Str2Int(String s, int defaultValue) {
		int result;
		try {
			result = Integer.parseInt(s);
		} catch (Exception e) {
			result = defaultValue;
		}
		return result;
	}

	public static long Str2Long(String s) {
		return Long.parseLong(s);
	}

	public static long Str2Long(String s, long defaultValue) {
		long result;
		try {
			result = Long.parseLong(s);
		} catch (Exception e) {
			result = defaultValue;
		}
		return result;
	}

	public static String getString(Collection<String> data) {
		if (isEmpty(data)) {
			return null;
		}
		StringBuilder result = new StringBuilder();
		boolean first = true;
		// 第一个前面不拼接","
		for (String str : data) {
			if (first) {
				first = false;
			} else {
				result.append(",");
			}
			result.append(str);
		}
		return result.toString();
	}

	public static boolean isEmpty(Object value) {
		return value == null;
	}

	public static boolean isEmpty(String value) {
		return value == null || value.isEmpty();
	}

	public static boolean isEmpty(Boolean value) {
		return value == null;
	}

	public static boolean isEmpty(Integer value) {
		return value == null || value == Integer.MAX_VALUE || value == Integer.MIN_VALUE;
	}

	public static boolean isEmpty(Double value) {
		return value == null || value.isNaN();
	}

	/**
	 * List对象是否为空（null或长度小于1返回true）
	 *
	 * @param value
	 * @return
	 */
	public static boolean isEmpty(List<?> value) {
		return value == null || value.size() < 1;
	}

	public static boolean isEmpty(Set<?> value) {
		return value == null || value.size() < 1;
	}

	public static boolean isValidateDate(String s) {
		if (isEmpty(s)) {
			return false;
		}
		try {
			LocalDate.parse(s);
			return true;
		} catch (DateTimeParseException e) {
			return false;
		}
	}

	public static byte[] getBytesFromFile(String file) throws IOException {
		return getBytes(new FileInputStream(file));
	}

	public static byte[] getBytesFromResource(String resource) throws IOException {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		byte[] bytes = getBytes(classLoader.getResourceAsStream(resource));

		return bytes;
	}

	public static byte[] getBytes(InputStream input) throws IOException {
		ByteArrayOutputStream output = null;
		try {
			output = new ByteArrayOutputStream();

			byte buffer[] = new byte[1024];
			int length;
			while ((length = input.read(buffer)) >= 0) {
				output.write(buffer, 0, length);
			}

			return output.toByteArray();
		} finally {
			close(output);
			close(input);
		}
	}

	public static IOException close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			return e;
		}

		return null;
	}

//	public static String getFlowCategoryName(String category) {
//		String result;
//		if ("event".equalsIgnoreCase(category)) {
//			result = "关键事件";
//		} else if ("process".equalsIgnoreCase(category)) {
//			result = "非排产工�?";
//		} else if ("mainprocess".equalsIgnoreCase(category)) {
//			result = "排产工序";
//		} else {
//			result = "�?";
//		}
//		return result;
//	}

	public static int compareTo(String a, String b) {
		if (Objects.equals(a, b)) {
			return 0;
		} else if (a != null && b != null) {
			return a.compareTo(b);
		} else {
			return a==null?-1:1;
		}
	}

	public static int compareTo(LocalDate a, LocalDate b) {
		if (Objects.equals(a, b)) {
			return 0;
		} else if (a != null && b != null) {
			return a.compareTo(b);
		} else {
			return a==null?-1:1;
		}
	}
	public static int compareTo(LocalDateTime a, LocalDateTime b) {
		if (Objects.equals(a, b)) {
			return 0;
		} else if (a != null && b != null) {
			return a.compareTo(b);
		} else {
			return a==null?-1:1;
		}
	}

	public static int compareTo(Integer a, Integer b) {
		if (Objects.equals(a, b)) {
			return 0;
		} else if (a != null && b != null) {
			return a - b;
		} else {
			return a==null?-1:1;
		}
	}

	public static int compareTo(Double a, Double b) {
		if (Objects.equals(a, b)) {
			return 0;
		} else if (a != null && b != null) {
			return a.compareTo(b);
		} else {
			return a==null?-1:1;
		}
	}

	public static boolean equals(String a, String b) {
		if (a == null && b == null) {
			return true;
		}
		if (a != null) {
			return a.equals(b);
		} else {
			return b.equals(a);
		}
	}

	public static boolean equals(Integer a, Integer b) {
		if (a == null && b == null) {
			return true;
		}
		if (a != null) {
			return a.equals(b);
		} else {
			return b.equals(a);
		}
	}

	public static boolean equals(LocalDateTime a, LocalDateTime b) {
		if (a == null && b == null) {
			return true;
		}
		if (a != null) {
			return a.equals(b);
		} else {
			return b.equals(a);
		}
	}

	public static boolean equals(LocalDate a, LocalDate b) {
		if (a == null && b == null) {
			return true;
		}
		if (a != null) {
			return a.equals(b);
		} else {
			return b.equals(a);
		}
	}

	public static boolean equals(Double a, Double b) {
		if (a == null && b == null) {
			return true;
		}
		if (a != null) {
			return a.equals(b);
		} else {
			return b.equals(a);
		}
	}

	public static String List2Str(List<String> src) {
		return List2Str(src, ",");
	}

	public static String List2Str(List<String> src, String separator) {
		if (!Util.isEmpty(src)) {
			StringBuilder sb = new StringBuilder();
			for (String element : src) {
				if (isEmpty(element)) {
					continue;
				} else {
					sb.append(separator).append(element);
				}
			}
			if (sb.length() > 1) {
				return sb.substring(1);
			}
		}
		return null;
	}

	public static String getLikeString(String value) {
		if (isEmpty(value)) {
			return null;
		}
		if (value.indexOf("%") < 0) {
			return "%" + value + "%";
		} else {
			return value;
		}
	}

	/**
	 *
	 * @param suffix
	 * @param fill
	 * @param totalLength
	 * @return
	 */
	public static String getLeftPadding(String suffix, char fill, int totalLength) {
		return getFillString("", suffix, fill, totalLength);
	}

	public static String getRightPadding(String prefix, char fill, int totalLength) {
		return getFillString(prefix, "", fill, totalLength);
	}

	public static String getFillString(String prefix, String suffix, char fill, int totalLength) {
		int c = 0;
		int needLength = totalLength - (prefix.length() + suffix.length());

		StringBuilder sb = new StringBuilder();
		sb.append(prefix);
		while (c < needLength) {
			sb.append(fill);
			c++;
		}
		sb.append(suffix);
		return sb.toString();
	}

	/**
	 * 16进制字符串转换成为正常显示字符串(无需Unicode解码)
	 *
	 * @param hexStr
	 * @return
	 */
	public static String hexStr2Str(String hexStr) {
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;
		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}

	public static List<String> getLocalIPList() {
		List<String> ipList = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			NetworkInterface networkInterface;
			Enumeration<InetAddress> inetAddresses;
			InetAddress inetAddress;
			String ip;
			while (networkInterfaces.hasMoreElements()) {
				networkInterface = networkInterfaces.nextElement();
				inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
						ip = inetAddress.getHostAddress();
						ipList.add(ip);
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ipList;
	}

	public static void delay(int mSecond) {
		if (mSecond > 0) {
			try {
				Thread.sleep(mSecond);
			} catch (Exception e) {

			}
		}
	}
	
	public static String getBrowseType(String userAgent) {
		System.out.println(userAgent);
		if(userAgent.contains("QQBrowser"))
	        return "QQBrowser";
		if(userAgent.contains("Edg"))
	        return "Edge";
	    else if(userAgent.contains("Chrome"))
	        return "Chrome";
	    else if(userAgent.contains("Firefox"))
	        return "Firefox";
		else if(userAgent.contains("MSIE"))
	        return "IE";
	    else if(userAgent.contains("Safari"))
	        return "Safari";
	    else
	        return "Unknown";		
	}

	public static void main(String[] args) {
		System.out.println(hexStr2Str("31323334"));
	}

}
